﻿using Repository;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SqlLiteTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {



            List<Student> books = new List<Student>()
            {
                new Student() { Name = "小明", Age = 11, Gender = "男" },
                new Student() { Name = "老王",  Age = 12, Gender = "男" },
                new Student() { Name = "小郭", Age = 10, Gender = "女" },
                new Student() { Name = "小李",  Age = 11, Gender = "男" },
                new Student() { Name = "小玉",  Age = 9, Gender = "女" },
            };

            using (var db = new StudentContext())
            {
                db.Students.AddRange(books);
                int count = db.SaveChanges();
                this.Text = $"{DateTime.Now}, 插入{count}条记录";
            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            using (var db = new StudentContext())
            {
                var students = db.Students.FirstOrDefault(x => x.Name == "小李");
                if (students != null)
                {
                    students.Age += 1;
                    int count = db.SaveChanges();
                    this.Text = $"{DateTime.Now}, 修改{count}条记录";
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            using (var db = new StudentContext())
            {
                var students = db.Students.FirstOrDefault(x => x.Name == "小玉");
                if (students != null)
                {
                    var result = db.Students.Remove(students);
                    int count = db.SaveChanges();
                    this.Text = $"{DateTime.Now}, 删除{count}条记录";
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            using (var db = new StudentContext())
            {
                var students = db.Students.Where(x => x.Name == "老王").OrderByDescending(x => x.Age).ToList();
                this.Text = $"{DateTime.Now}, 查到{students.Count}条记录";
                this.dataGridView1.DataSource = students;
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            using (var db = new StudentContext())
            {
                var students = db.Students.ToList();
                this.dataGridView1.DataSource = students;
            }
        }
    }
}
